<template>
  <div class="portrait">
    <img :src="img" ref="img">
    <div class="setting">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editUserImg } from '@/api/user'
export default {
  name: 'portrait',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  computed: {},
  watch: {},
  created () {

  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  methods: {
    onConfirm() {
      // 加载提示
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true,
        // 设置转动时间，为0就无限转动
        duration: 0
      })
      try {
        this.cropper.getCroppedCanvas().toBlob(async blob => {
          // 服务器要求的是formData对象
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await editUserImg(formData)
          this.$emit('updata-img', data.data.photo)
        })
        this.$toast.success('更新头像成功')
      } catch (err) {
        this.$toast.fail('更新头像失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.portrait {
  height: 100%;
  background-color: #000;
  img {
    display: block;
    max-width: 100%;
  }
  .setting {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
      width: 90px;
      height: 90px;
      line-height: 90px;
      text-align: center;
      color: #fff;
      font-size: 30px;
    }
  }
}
</style>
